import React, { Component } from 'react';
import {
  Col,
  Space,
  Row,
  Form,
  message,
  Button,
  Typography,
  Card,
  Upload,
  Modal,
  Tooltip,
} from 'antd';
import {
  UploadOutlined,
  DownloadOutlined,
  InfoCircleOutlined,
  CheckOutlined,
  ExclamationOutlined,
  InfoCircleTwoTone,
} from '@ant-design/icons';
import 'antd/dist/antd.css';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
// import moment from 'moment';
// import 'moment/locale/zh-cn';
import {
  getDictionaryLabel,
  getAjaxurl,
  devProTest,
} from '../../../rudexRou/OperatesCookie.js';
import { getUrl } from '../../../utils';

import {
  queryExamPaper,
  checkAnswer,
  endExam,
  getDateTime,
} from '../../../api3';
import { fileUploadPrompt } from '../../../api3/promptMessage.js';
// import HasPermi from '../../../componentJsx/common/hasPermi';
import NewModal from '../../../componentJsx/common/NewModal';
import '../../../componentCss/component.css';

export default class TakeExam extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      dataLoading: true,
      subjectList: [],
      examData: null,
      examPaperData: null,
      subjectData: null,
      submitModal: false,
      unfinishList: [],
    };
  }
  addForm = React.createRef();
  subjectForm = React.createRef();
  getExamPaper = (examDetailId) => {
    queryExamPaper({ examDetailId })
      .then((res) => {
        if (res.data.code == 200) {
          this.setState({
            dataLoading: false,
            examData: res.data.data,
            subjectData: res.data.data.questionAnswerPackageList,
          });
        } else {
          message.error(res.data.message || '试卷信息查询失败', 3);
          getUrl('/TmfsExam/MyPractice');
        }
      })
      .catch((err) => {
        message.error('试卷信息查询失败，请检查网络');
      });
  };
  submitExam = (goBack) => {
    let data = { examDetailId: this.state.examPaperData.examDetailId };
    endExam(data)
      .then((res) => {
        if (res.data.code == 200) {
          message.success('交卷成功', 3);
          if (goBack !== false) {
            getUrl('/TmfsExam/MyPractice');
          }
        } else {
          if (res.data.message == '你的参考资格已取消') {
            message.error(res.data.message, 3);
            getUrl('/TmfsExam/MyPractice');
          } else {
            message.error('交卷失败  ' + res.data.message, 3);
          }
        }
      })
      .catch((err) => {
        message.error('交卷失败，请检查你的网络连接', 3);
      });
  };
  showSubmitModal = () => {
    let subjectData = [...this.state.subjectData];
    let unfinishList = [];
    subjectData.forEach((item, index) => {
      if (item.answer && item.answer.answerUrl) {
      } else {
        if (item.answer) {
          unfinishList.push({
            title: '题目' + (index + 1),
            errorMessage: item.answer.errorMessage || '答案文件未上传',
          });
        } else {
          unfinishList.push({
            title: '题目' + (index + 1),
            errorMessage: '答案文件未上传',
          });
        }
      }
    });
    this.setState({ unfinishList, submitModal: true });
  };
  hiddenModal = () => {
    this.setState({ submitModal: false, unfinishList: [] });
  };
  saveExam = () => {
    console.log('保存试卷');
  };
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  scrollToAnchor = (anchorName) => {
    if (anchorName) {
      // 找到锚点
      const anchorElement = document.getElementById(anchorName);
      // 如果对应id的锚点存在，就跳转到锚点
      if (anchorElement) {
        anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
      }
    }
  };
  uploadFile = (answer, index) => {
    let subjectData = [...this.state.subjectData];
    subjectData[index]['answer'] = answer;
    if (answer.errorMessage)
      subjectData[index]['answer'].errorMessage = answer.errorMessage;
    this.setState({ subjectData });
  };
  timeEnd = () => {
    this.submitExam(false);
    let secondsToGo = 5;
    const modal = Modal.success({
      title: '练习时间已结束！',
      content: `系统已自动提交试卷， ${secondsToGo} 秒后返回首页~`,
    });
    const timer = setInterval(() => {
      secondsToGo -= 1;
      modal.update({
        content: `系统已自动提交试卷， ${secondsToGo} 秒后返回首页~`,
      });
    }, 1000);
    setTimeout(() => {
      clearInterval(timer);
      modal.destroy();
      getUrl('/TmfsExam/MyPractice');
    }, secondsToGo * 1000);
  };
  componentWillMount() {
    let examPaperData = JSON.parse(sessionStorage.getItem('examPaperData'));
    if (examPaperData) {
      this.setState({ examPaperData });
      this.getExamPaper(examPaperData.examDetailId);
    } else {
      getUrl('/TmfsExam/MyPractice');
    }
  }
  componentDidMount() {}
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    return (
      <div style={{ padding: '0px 20px 20px 30px', position: 'relative' }}>
        {this.state.dataLoading ? (
          <div></div>
        ) : (
          <>
            <Row wrap={false}>
              <Col flex='auto'>
                <Row gutter={[20, 20]}>
                  <Col span={24}>
                    <Card style={{ borderColor: '#ddd' }}>
                      <Row wrap={false} gutter={[40]}>
                        <Col>练习名称：{this.state.examData.examName}</Col>
                        <Col>
                          练习语言：
                          {getDictionaryLabel(
                            'language',
                            this.state.examData.language
                          )}
                        </Col>
                        <Col>
                          练习级别：
                          {getDictionaryLabel(
                            'examLevel',
                            this.state.examData.level
                          )}
                        </Col>
                        <Col>练习时长：{this.state.examData.duration} min</Col>
                      </Row>
                    </Card>
                  </Col>
                  {this.state.subjectData.map((item, index) => {
                    return (
                      <Col span={24} key={index + 1}>
                        <div
                          name={'components' + (index + 1)}
                          id={'components' + (index + 1)}
                        >
                          <ExamCard
                            index={index}
                            uploadFile={this.uploadFile}
                            subjectInfo={item}
                            examPaperData={this.state.examPaperData}
                            language={this.state.examData.language}
                          />
                        </div>
                      </Col>
                    );
                  })}
                </Row>
              </Col>
              <Col flex='180px'></Col>
            </Row>

            <Row style={{ marginTop: '40px' }}>
              <Col span={24}>
                <Space size='middle'>
                  {/* <Button onClick={this.saveExam}>保存</Button> */}
                  <Button
                    type='primary'
                    onClick={this.showSubmitModal}
                    loading={this.state.confirmLoading}
                  >
                    交卷
                  </Button>
                </Space>
              </Col>
            </Row>

            <div
              style={{
                position: 'fixed',
                top: '134px',
                right: '60px',
                width: '156px',
                border: '1px solid #ddd',
                padding: '24px 10px 10px',
              }}
            >
              <Row gutter={[20, 10]}>
                <Col span={24}>
                  <CountDown
                    endTime={this.state.examPaperData.endTime}
                    timeEnd={this.timeEnd}
                  />
                </Col>
                <Col span={24}>题目列表：</Col>
                {this.state.subjectData.map((item, index) => {
                  return (
                    <Col span={24} key={index + 1}>
                      <a
                        onClick={() =>
                          this.scrollToAnchor('components' + (index + 1))
                        }
                      >
                        <Space>
                          <span>题目{index + 1}</span>

                          {item.answer && item.answer.answerUrl ? (
                            <CheckOutlined style={{ color: '#0f0' }} />
                          ) : (
                            <ExclamationOutlined style={{ color: '#f00' }} />
                          )}
                        </Space>
                      </a>
                    </Col>
                  );
                })}
              </Row>
            </div>
          </>
        )}

        <NewModal
          modalOptions={{
            width: '400px',
            title: '提交试卷',
            visible: this.state.submitModal,
            onCancel: this.hiddenModal,
            destroyOnClose: true,
          }}
          buttonOptions={{
            position: 'right',
            btnList: [
              {
                key: 1,
                onClick: this.hiddenModal,
                text: '取消',
              },
              {
                key: 0,
                onClick: this.submitExam,
                text: '确定',
                type: 'primary',
                loading: this.state.confirmLoading,
              },
            ],
          }}
        >
          <InfoCircleOutlined
            style={{
              fontSize: '28px',
              color: '#e00',
              float: 'left',
              backgroundColor: '#f002',
              padding: 8,
              borderRadius: '50%',
            }}
          />
          {/* <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              // height: 44,
              lineHeight: '44px',
            }}
          > 
            提交试卷并结束练习?
          </div> */}
          <div
            style={{
              fontSize: 14,
              marginLeft: 60,
              fontWeight: 700,
              // height: 44,
              // lineHeight: '44px',
            }}
          >
            <p style={{ lineHeight: '44px' }}>
              {this.state.unfinishList.length >= 1
                ? '以下题目未完成，确定提交试卷并结束练习？'
                : '提交试卷并结束练习?'}
            </p>
            {this.state.unfinishList.map((item, index) => {
              return (
                <p key={index}>
                  {item.title}：<span>{item.errorMessage}</span>
                </p>
              );
            })}
          </div>
        </NewModal>
      </div>
    );
  }
}

class ExamCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      subjectInfo: this.props.subjectInfo,
      examPaperData: this.props.examPaperData,
      fileList: [],
      answer: this.props.subjectInfo.answer,
      tempFilePath: null,
      checkMessage: [],
      uploadLoading: false,
      downloadLoading: false,
    };
  }
  answerForm = React.createRef();
  checkAnswer = () => {
    let data = {};
    let answer = this.state.answer;
    if (answer && answer.id) data.id = answer.id;
    if (answer && answer.answerUrl) data.answerUrl = answer.answerUrl;
    if (answer && answer.testexamDetailId) {
      data.testexamDetailId = answer.testexamDetailId;
    } else {
      data.testexamDetailId = this.state.examPaperData.examDetailId;
    }
    if (answer && answer.testexamQuestionId) {
      data.testexamQuestionId = answer.testexamQuestionId;
    } else {
      data.testexamQuestionId = this.state.subjectInfo.ttestexamQuestionId;
    }
    data.tempFilePath = this.state.tempFilePath;
    checkAnswer(data)
      .then((res) => {
        if (res.data.code == 200) {
          if (res.data.data.errorMessage) {
            this.setState({
              uploadLoading: false,
              checkMessage: res.data.data.errorMessage.split('@123@'),
              answer: res.data.data,
            });
            message.error('检测不通过', 3);
          } else {
            message.success('检测通过', 3);
            this.setState({
              uploadLoading: false,
              checkMessage: ['检测通过'],
              answer: res.data.data,
            });
          }
          this.props.uploadFile(res.data.data, this.props.index);
        } else {
          if (res.data.message == '你的参考资格已取消') {
            message.error(res.data.message, 3);
            getUrl('/TmfsExam/MyPractice');
          } else {
            message.error(res.data.message || '检测失败', 3);
            this.setState({ uploadLoading: false, checkMessage: ['检测失败'] });
          }
        }
      })
      .catch((err) => {
        message.error('检测失败', 3);
        console.log(err);
        this.setState({ uploadLoading: false, checkMessage: ['检测失败'] });
      });
  };
  componentWillMount() {
    if (
      this.props.subjectInfo.answer &&
      this.props.subjectInfo.answer.answerUrl
    ) {
      this.setState({ checkMessage: ['文件已上传并检测通过'] });
    } else {
      this.setState({ checkMessage: ['文件未上传'] });
    }
  }
  tooltipTitle = () => {
    return fileUploadPrompt[this.props.language]['exam'].map((item, index) => {
      return <div key={index}>{item}</div>;
    });
  };
  render() {
    const authToken = window.localStorage.getItem('authToken');
    const token = window.localStorage.getItem('refreshToken');
    let url = getAjaxurl() + `/tmfsExamPlatform/file/upload`;
    if (devProTest() === 'develop') {
      url = window.location.origin + `/tmfsExamPlatform/file/upload`;
    }
    const props = {
      action: url,
      name: 'file',
      accept: '.zip',
      headers: {
        refreshToken: token,
        authToken: authToken,
      },
      showUploadList: { showRemoveIcon: false },
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
            // textType: 'secondary',
            // text: '请上传文件',
          };
        });
      },
      onChange: (info) => {
        const { status } = info.file;
        if (status !== 'uploading') {
        }
        if (status === 'done') {
          if (info.file.response.code == 200) {
            // message.success(`上传成功`, 3);
            this.setState({ tempFilePath: info.file.response.data }, () => {
              this.checkAnswer();
            });
          } else if (info.file.response.code == 500) {
            message.error(
              info.file.response.message || `文件上传失败，请重新上传`,
              3
            );
            this.setState({
              uploadLoading: false,
              checkMessage:
                info.file.response.message || '文件上传失败，请重新上传',
            });
          } else {
            message.error(`文件上传失败，请重新上传`, 3);
            this.setState({
              uploadLoading: false,
              checkMessage: '文件上传失败，请重新上传',
            });
          }
        } else if (status === 'error') {
          message.error(`文件上传失败，请重新上传`, 3);
          this.setState({
            uploadLoading: false,
            checkMessage: '文件上传失败，请重新上传',
          });
        }
      },
      beforeUpload: (file, fileList) => {
        this.setState({ uploadLoading: true });
        return true;
      },
    };
    return (
      <div>
        <Row wrap={false}>
          <Col flex='auto'>
            <Card style={{ borderColor: '#ddd', borderRight: 'none' }}>
              <Typography.Title level={5}>题目描述</Typography.Title>

              <BraftEditor
                readOnly={true}
                controls={[]}
                contentStyle={{
                  height: '600px',
                }}
                defaultValue={BraftEditor.createEditorState(
                  this.state.subjectInfo.description
                )}
                // value={editorState}
              />
            </Card>
          </Col>
          <Col flex='360px'>
            <Card style={{ borderColor: '#ddd', height: '100%' }}>
              <Typography.Title level={5}>题目信息</Typography.Title>
              <Form>
                <Form.Item label='题目名称'>
                  {this.state.subjectInfo.title}
                </Form.Item>
                <Form.Item label='题目分值'>
                  {this.state.subjectInfo.score}
                </Form.Item>
                <Form.Item label='题目下载'>
                  <Button
                    loading={this.state.downloadLoading}
                    href={this.state.subjectInfo.questionPackage}
                    icon={<DownloadOutlined />}
                  >
                    点击下载
                  </Button>
                </Form.Item>
              </Form>
              <Typography.Title level={5} style={{ marginTop: '30px' }}>
                答案上传
              </Typography.Title>
              <Form>
                {/* <Form.Item label='练习语言'>JAVA</Form.Item> */}
                <Form.Item label='上传附件'>
                  <Upload
                    {...props}
                    style={{ width: '100%' }}
                    maxCount={1}
                    disabled={this.state.uploadLoading}
                  >
                    <Space>
                      <Button
                        disabled={this.state.uploadLoading}
                        icon={<UploadOutlined />}
                      >
                        点击上传
                      </Button>
                      <Tooltip
                        title={() => {
                          return this.tooltipTitle();
                        }}
                      >
                        {/* <InfoCircleTwoTone /> */}
                        <Typography.Text
                          type='secondary'
                          style={{ fontSize: '12px', lineHeight: '12px' }}
                        >
                          {' 必传文件说明'}
                        </Typography.Text>
                      </Tooltip>
                    </Space>
                  </Upload>
                </Form.Item>
                <Form.Item label='检测结果'>
                  <div
                    style={{
                      border: '1px solid #ddd',
                      minHeight: '32px',
                      lineHeight: '30px',
                      padding: '0 10px',
                    }}
                  >
                    {this.state.checkMessage.map((item, index) => {
                      return <div key={index}>{item}</div>;
                    })}
                  </div>
                </Form.Item>
              </Form>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
//倒计时
class CountDown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      day: '-',
      hour: '-',
      minute: '-',
      second: '-',
    };
  }
  componentWillMount() {
    this.getNowDate();
  }
  componentDidMount() {}
  //组件卸载取消倒计时
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  getNowDate = () => {
    getDateTime()
      .then((res) => {
        let nowDate = new Date(res.data.data).getTime();
        if (this.props.endTime) {
          let endTime = this.props.endTime.replace(/-/g, '/');
          this.countFun(endTime, nowDate);
        }
      })
      .catch((err) => {
        let nowDate = new Date().getTime();
        if (this.props.endTime) {
          let endTime = this.props.endTime.replace(/-/g, '/');
          this.countFun(endTime, nowDate);
        }
      });
  };
  countFun = (endTime, nowDate) => {
    let end_time = new Date(endTime).getTime(),
      sys_second = end_time - nowDate;
    this.timer = setInterval(() => {
      //防止倒计时出现负数
      if (sys_second > 1000) {
        sys_second -= 1000;
        let day = Math.floor(sys_second / 1000 / 3600 / 24);
        let hour = Math.floor((sys_second / 1000 / 3600) % 24);
        let minute = Math.floor((sys_second / 1000 / 60) % 60);
        let second = Math.floor((sys_second / 1000) % 60);
        this.setState({
          day: day,
          hour: hour < 10 ? '0' + hour : hour,
          minute: minute < 10 ? '0' + minute : minute,
          second: second < 10 ? '0' + second : second,
        });
      } else {
        clearInterval(this.timer);
        //倒计时结束时触发父组件的方法
        this.props.timeEnd();
      }
    }, 1000);
  };
  render() {
    return (
      <div>
        <div>剩余练习时间：</div>
        <div style={{ fontWeight: 700, fontSize: 32, color: '#d00' }}>
          {this.state.day > 0
            ? `${this.state.day}天${this.state.hour}:${this.state.minute}:${this.state.second}`
            : `${this.state.hour}:${this.state.minute}:${this.state.second}`}
          {/* {this.state.hour}:{this.state.minute}:{this.state.second} */}
        </div>
      </div>
    );
  }
}
